import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.factory.CommonFactoryFinder;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.identity.FeatureId;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ShpOperation {
    public void testGetPropertiesNoGeometry() throws Exception {
        String path = "E:\\9.1GISData\\Lambert\\地级城市驻地.shp";
        String path2 = "E:\\1.SourceCodeGit\\ServerCode2\\GISServer\\target\\test-classes\\polygon2single.shpLine_1.shp";
        File file = new File(path);
        System.out.println("从File获取的结果：" + file.getName().substring(0, file.getName().lastIndexOf('.')));
        SimpleFeatureSource sfsSource = ((SimpleFeatureSource) ShpfileReader.getShpfile2(path2, "UTF8"));
        SimpleFeatureIterator itSource = sfsSource.getFeatures().features();
        SimpleFeature feature = itSource.next();
        for (Property property : feature.getProperties()) {
//            System.out.println(feature.getDefaultGeometryProperty().getName());//几何列名还是the_geom
            System.out.println("列名：" + property.getName());
            System.out.println("属性类型：" + property.getType().getBinding().toString());
        }
    }

    //TODO：这里shp导出的Excel如果是新建的，就会打开失败，需要解决这个问题
    public void testShpToExcel() {
        try {
            String pathShp = "E:\\9.1GISData\\mygeo2shp_1.shp";
            String pathExcel = "E:\\vectorOutput\\shp2excel3.xlsx";
            //问题出在“新建Excel”这个过程中，当前使用已有的Excel时并不会报错，但是新建的话，就是报错导致Excel无法打开
            Shp2Excel lpOperation = new Shp2Excel(pathShp, pathExcel);
            lpOperation.exportAttr2Excel();
            System.out.println("执行成功");
        } catch (Exception error) {
            System.out.println("导出Excel失败，" + error.getLocalizedMessage());
        }
    }

    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();

    /*
    * 异常情况说明：
    * 按照下面的删除方式删除了fid=1的数据，然后再次进行查询时，总是查询不到该要素；
    * 但实际上通过遍历的方式，可以看到shp中是存在fid=1的记录的，不知道为什么获取不到;
    * 是删除的流程没有走对？还是其他原因？
    * */
    public void testShpEdit() {
        try {
            String pathShp = "E:\\9.1GISData\\mygeo2shp_1.shp";
            String fid = "1";
            Transaction transDelete = new DefaultTransaction("update");//这里的名字指的是‘事务的名称’，并不指代操作的类型
            SimpleFeatureSource sfs = ShpfileReader.getShpfile2(pathShp, "UTF-8");
            System.out.println("删除前要素的总数："+sfs.getFeatures().size());
//            SimpleFeatureStore sfStore = (SimpleFeatureStore) sfs;//可以直接强制转换
//            sfStore.setTransaction(transDelete);
            String typeName = sfs.getSchema().getTypeName();
            Set<FeatureId> fidsToDelete = new HashSet<>();
            fidsToDelete.add(ff.featureId(typeName + "." + fid));
//            fidsToDelete.add(ff.featureId("mygeo2shp_1.1"));//删除一条数据之后，无法获取fid=1的记录了；大于1的记录仍然你可以获取
//            Filter filterDelete = ff.id(fidsToDelete);
//            sfStore.removeFeatures(filterDelete);
//            transDelete.commit();
//            transDelete.close();
            Filter filter = ff.id(Collections.singleton(ff.featureId(typeName + "." + fid)));
            SimpleFeatureCollection sfcFeas = sfs.getFeatures(filter);
            if (sfcFeas.size()>0) {
                SimpleFeature featureSelected= sfcFeas.features().next();
                System.out.println("getID方法结果："+featureSelected.getID());
                System.out.println("选中的要素是："+featureSelected.getAttribute("name"));
            }else {
                System.out.println("没有找到要素");
            }
            //释放shp内存连接
//            DataStore dsShp= (DataStore)sfs.getDataStore();
//            dsShp.dispose();
//            fidsToDelete.clear();
            sfs.getDataStore().dispose();
            System.out.println("成功执行");
        } catch (Exception error) {
            System.out.println("执行失败");
            System.out.println(error.getLocalizedMessage());
        }
    }
}
